package com.mds.dmd.core.service;

import com.haulmont.cuba.core.global.Messages;
import com.mds.dmd.core.AppBlock;
import com.mds.dmd.core.config.DBDriverConfig;
import com.mds.dmd.entity.DBType;
import com.mds.dmd.entity.TargetDB;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

@Service(TargetDBConnService.NAME)
public class TargetDBConnServiceBean implements TargetDBConnService {
    @Inject
    DBDriverConfig dbDriverConfig;

    @Inject
    Messages messages;

    @Override
    public Connection createConn(@NotNull TargetDB db) throws ClassNotFoundException, SQLException {
        Connection conn=null;
        String driverClassName="";
        if(db.getDbType().equals(DBType.MYSQL)){
            driverClassName=dbDriverConfig.getMysql();
        }else if(db.getDbType().equals(DBType.ORACLE)){
            driverClassName=dbDriverConfig.getOracle();
        }

        if(StringUtils.isBlank(driverClassName))
            throw new ClassNotFoundException(messages.getMessage(AppBlock.THIS_PACKAGE,"dmd_TargetDBConnService.dbDriverNotFound"));

        Class.forName(driverClassName);

        conn = DriverManager.getConnection(db.getDbUrl(),db.getDbUserName(),db.getDbPassword());
        return conn;
    }
}